﻿using CodeCity.SDK.Contracts;
using System;
using System.Net.Http;
using System.Text;
using System.Text.Json;
using System.Threading.Tasks;

namespace CodeCity.SDK
{
    public class GameConnection
    {
        private string username;
        private string password;
        private static HttpClient httpClient = new HttpClient();


        static GameConnection()
        {
            httpClient.BaseAddress = new Uri("http://server.gamebrain.world");
        }

        /// <summary>
        /// 登录成功后的Token
        /// </summary>
        public static string AccessToken { get; private set; }

        public async Task<CityModel> GetCityAsync()
        {
            var responseMessage = await httpClient.GetAsync("/api/zion/sync");
            var responseResult = await responseMessage.Content.ReadAsStringAsync();
            if (responseMessage.StatusCode == System.Net.HttpStatusCode.Unauthorized)
            {
                throw new NotOnlineException();
            }
            if (responseMessage.StatusCode != System.Net.HttpStatusCode.OK)
            {
                throw new OperationException(responseResult);
            }

            var cityModel = JsonSerializer.Deserialize<CityModel>(responseResult, new JsonSerializerOptions()
            {
                PropertyNameCaseInsensitive = true
            });
            return cityModel;
        }

        /// <summary>
        /// 使用用户名和密码登录服务器，如果登录失败，会抛出<seealso cref="OperationException"/>异常
        /// </summary>
        /// <returns></returns>
        /// <exception cref="OperationException"></exception>
        public async Task ConnectAsync(string username, string password)
        {
            var loginContent = new StringContent(JsonSerializer.Serialize(new
            {
                Username = username,
                Password = password
            }), Encoding.UTF8, "application/json");
            var responseMessage = await httpClient.PostAsync("/api/zion/login", loginContent);
            var responseresult = await responseMessage.Content.ReadAsStringAsync();
            if (responseMessage.StatusCode != System.Net.HttpStatusCode.OK)
            {
                throw new OperationException(responseresult);
            }
            AccessToken = responseresult.Trim('\'').Trim('\"');
            httpClient.DefaultRequestHeaders.Remove("Authorization");
            httpClient.DefaultRequestHeaders.Add("Authorization", "Bearer " + AccessToken);
        }
    }
}
